-- LuaTools需要PROJECT和VERSION这两个信息
PROJECT = "ballclock"
VERSION = "1.0.0"

-- 引入必要的库文件(lua编写), 内部库不需要require
local sys = require "sys"
_G.mqtt = require("mqtt")

local uartid = 2

--初始化
local result = uart.setup(
    uartid,--串口id
    115200,--波特率
    8,--数据位
    1--停止位
)

uart.on(uartid, "receive", function(id, len)
    local data = uart.read(id, len)
    if 100==tonumber(data) then
        os.exit()
    end
    log.info("uart", id, len, data)
    pwm.open(5, 200, tonumber(data))
end)

sys.subscribe("WLAN_READY", function ()
    print("!!! wlan ready event !!!")
end)
sys.subscribe("NTP_UPDATE", function(re)
    log.info("ntp", "result", re)
end)
function mins_low()
    pwm.open(5, 200, 16)
    sys.wait(1000)
    pwm.open(5, 200, 32)
    sys.wait(1000)
    pwm.open(5, 200, 27)
end

function mins_high()
    pwm.open(5, 200, 14)
    sys.wait(1000)
    pwm.open(5, 200, 16)
    sys.wait(1000)
    pwm.open(5, 200, 27)
    sys.wait(1000)
    pwm.open(5, 200, 32)
    sys.wait(1000)
    pwm.open(5, 200, 27)
end

function hour()
    pwm.open(5, 200, 11)
    sys.wait(1000)
    pwm.open(5, 200, 14)
    sys.wait(1000)
    pwm.open(5, 200, 16)
    sys.wait(1000)
    pwm.open(5, 200, 27)
    sys.wait(1000)
    pwm.open(5, 200, 29)
    sys.wait(1000)
    pwm.open(5, 200, 32)
    sys.wait(1000)
    pwm.open(5, 200, 27)
end

sys.taskInit(function()
    wlan.setMode("wlan0", wlan.STATION)
    -- 连接到自己的WiFi热点中
    wlan.connect("SSID", "password")
    print("wait for WLAN_READY")
    sys.waitUntil("WLAN_READY", 30000)
    if wlan.ready() then
        socket.ntpSync()
        sys.waitUntil("NTP_UPDATE", 30000)
        print(os.date())
        local Hour_old=tonumber(os.date("%I"))
        local Mins_H_old=os.date("%M")//10
        local Mins_L_old=os.date("%M")%10
        local Hour_new=Hour_old
        local Mins_H_new=Mins_H_old
        local Mins_L_new=Mins_L_old
        while 1 do
            print("date:", os.date())
            Hour_new=tonumber(os.date("%I"))
            Mins_H_new=os.date("%M")//10
            Mins_L_new=os.date("%M")%10
            if Hour_new~=Hour_old then
                hour()
            elseif Mins_H_new~=Mins_H_old then
                mins_high()
            elseif Mins_L_new~=Mins_L_old then
                mins_low()
            end
            Hour_old=Hour_new
            Mins_H_old=Mins_H_new
            Mins_L_old=Mins_L_new
            
            if 5==Mins_L_new then
                if 30==tonumber(os.date("%S")) then
                    socket.ntpSync()
                    log.info("ntp:", "ntpsync")
                end
            end
            sys.wait(1000)
        end
    else
        print("wlan NOT ready!!!!")
    end
end)

sys.taskInit(function()
    -- 根据自己的服务器进行填写
    local host, port, selfid = "mqtt.server.ip", 1883, wlan.getMac():lower()
    -- 等待联网成功
    while true do
        while not socket.isReady() do 
            log.info("net", "wait for network ready")
            sys.waitUntil("NET_READY", 1000)
        end
        log.info("main", "mqtt loop")
        
        collectgarbage("collect")
        collectgarbage("collect")
        local mqttc = mqtt.client(wlan.getMac(), nil, nil, false)
        while not mqttc:connect(host, port) do sys.wait(2000) end
        local topic_req = string.format("/ballclock/%s/req", selfid)
        local topic_report = string.format("/ballclock/%s/report", selfid)
        log.info("mqttc", "mqtt seem ok", "try subscribe", topic_req)
        if mqttc:subscribe(topic_req) then
            log.info("mqttc", "mqtt subscribe ok", "try publish")
            if mqttc:publish(topic_report, "test publish " .. os.time(), 1) then
                while true do
                    log.info("mqttc", "wait for new msg")
                    local r, data, param = mqttc:receive(120000, "pub_msg")
                    log.info("mqttc", "mqttc:receive", r, data, param)
                    if r then
                        log.info("mqttc", "get message from server", data.payload or "nil", data.topic)
                        if data.payload == "hour" then
                            log.info("mqttc", "recv hour", data, param)
                            hour()
                        elseif data.payload == "minsh" then
                            log.info("mqttc", "recv mins high", data, param)
                            mins_high()
                        elseif data.payload == "minsl" then
                            log.info("mqttc", "recv mins low", data, param)
                            mins_low()
                        end
                    else
                        log.info("mqttc", "ok, something happen")
                        -- break
                    end
                end
            end
        end
        mqttc:disconnect()
        sys.wait(5000)
    end
end)
-- 用户代码已结束---------------------------------------------
-- 结尾总是这一句
sys.run()
-- sys.run()之后后面不要加任何语句!!!!!
